<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button type="primary" @click="handleAdd">添加菜单</el-button>
    </div>
    
    <el-table
      v-loading="loading"
      :data="menuList"
      border
      style="width: 100%"
      row-key="menuId"
    >
      <el-table-column prop="menuId" label="ID" width="80" align="center" />
      <el-table-column prop="menuName" label="菜单名称" min-width="150" />
      <el-table-column prop="menuUrl" label="菜单URL" min-width="150" />
      <el-table-column prop="orderNum" label="排序" width="100" align="center" />
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 菜单表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单URL" prop="menuUrl">
          <el-input v-model="form.menuUrl" placeholder="请输入菜单URL" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMenuList, saveOrUpdateMenu, deleteMenu, getMenuPage } from '@/api/menu'
import { handlePageResponse } from '@/utils/pagination'

// 菜单列表
const menuList = ref([])
// 加载状态
const loading = ref(false)
// 提交加载状态
const submitLoading = ref(false)
// 表单对话框可见状态
const dialogVisible = ref(false)
// 表单对话框标题
const dialogTitle = ref('添加菜单')
// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  menuId: null,
  menuName: '',
  menuUrl: '',
  orderNum: 0
})

// 表单验证规则
const rules = {
  menuName: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  menuUrl: [
    { required: true, message: '请输入菜单URL', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 分页相关数据
const total = ref(0)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
})

// 初始化数据
onMounted(async () => {
  await fetchData()
})

// 获取菜单列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getMenuPage(queryParams)
    const { list, total: totalCount } = handlePageResponse(res)
    menuList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('获取菜单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理添加菜单
const handleAdd = () => {
  dialogTitle.value = '添加菜单'
  resetForm()
  dialogVisible.value = true
}

// 处理编辑菜单
const handleEdit = (row) => {
  dialogTitle.value = '编辑菜单'
  resetForm()
  Object.assign(form, row)
  dialogVisible.value = true
}

// 处理删除菜单
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除菜单 "${row.menuName}" 吗？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteMenu(row.menuId)
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      await fetchData()
    } catch (error) {
      console.error('删除菜单失败:', error)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 重置表单
const resetForm = () => {
  form.menuId = null
  form.menuName = ''
  form.menuUrl = ''
  form.orderNum = 0
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      await saveOrUpdateMenu(form)
      ElMessage({
        type: 'success',
        message: form.menuId ? '更新成功!' : '添加成功!'
      })
      dialogVisible.value = false
      await fetchData()
    } catch (error) {
      console.error('保存菜单失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}
</script> 